part of 'delay_controller.dart';

///单位
enum UnitType { ms, cm, inc }

extension UnitTypeX on UnitType {
  List<String> get names => ['ms', 'cm', 'in'];
  List<double> get _steps => [0.02, 0.02, 0.02]; //[0.001, 1 / 34, 10 / 133.86];

  UnitType from(String name) {
    final i = names.indexOf(name);
    return UnitType.values[i];
  }

  String get name {
    var i = UnitType.values.indexOf(this);
    print(names[i]);
    return names[i];
  }

  ///步长
  double get step {
    var i = UnitType.values.indexOf(this);
    return _steps[i];
  }
}

class DelayItemController extends GetxController {
  LevelItemModel get level => DataMng().advancedModel.level.items[index];
  TimeDelayModel get timeDelay => DataMng().advancedModel.timeDelay;

  final TextEditingController textEditingController =
      TextEditingController(text: '3.60');

  DelayItemController(this.state) {
    debounce(delay, (v) => _sendData(), time: kMsgInterval);
    debounce(phase, (v) => _sendData(), time: kMsgInterval);
    debounce(mute, (v) {
      var volume = -this.volume * kVolumeRadio;
      Msg.msgVolume(index, volume.toInt(), mute: v).send();
    }, time: kMsgInterval);
    ever(phase, (v) {
      //找出其他联动通道
      if (!linked.value) return;
      for (var c in state.delayItemControllers) {
        if (!c.linked.value || c.index == index) continue;
        c.level.paraphase = v;
        c.phase.value = v;
      }
    });
    ever(mute, (v) {
      //找出其他联动通道
      if (!linked.value) return;
      for (var c in state.delayItemControllers) {
        if (!c.linked.value || c.index == index) continue;
        c.level.mute = v;
        c.mute.value = v;
      }
    });
    ever(
      volume,
      (v) {
        var volume = -v * kVolumeRadio;
        Msg.msgVolume(index, volume.toInt()).send();

        //找出其他联动通道
        if (!linked.value) return;
        for (var c in state.delayItemControllers) {
          if (!c.linked.value || c.index == index) continue;
          c.level.volume = v.toInt();
          c.volume.value = v;
        }
      },
    );
    ever(linked, (v) {
      if (v) {
        //link时激活对应通道
        activeGain.value = true;
        //标记为被参考联动的通道
        if (state.linkedFirst.value == null) {
          state.linkedFirst.value = index;
        }
        //下发一次数据
        _asyncFirstLinkData();
      } else {
        //取消联动，更新最新参考联动
        if (state.linkedFirst.value != index) return;
        int? newLinkedIndex; //最新参考linked
        for (var i = 0; i < state.delayItemControllers.length; i++) {
          final c = state.delayItemControllers[i];
          if (c.linked.value && c.index != index) {
            newLinkedIndex = i;
            break;
          }
        }
        state.linkedFirst.value = newLinkedIndex;
      }
    });
  }

  final DelayController state;

  ///当前通道
  var index = 0;

  ///延时
  final delay = 0.0.obs;

  ///通道音量
  final volume = 0.0.obs;

  ///是否静音
  final mute = false.obs;

  ///反相
  final phase = false.obs;

  ///联动
  final linked = false.obs;

  ///是否激活
  final active = false.obs;

  ///是否激活
  final activeGain = false.obs;

  void refreshDelayText() {
    textEditingController.zftext = delayString(unitType: state.unit.value);
  }

  ///单位格式化
  String delayString({required UnitType unitType}) {
    switch (unitType) {
      case UnitType.ms:
        return delay.toStringAsFixed(2);
      case UnitType.cm:
        return (delay * 34).toStringAsFixed(2);
      case UnitType.inc:
        return (delay * 13.386).toStringAsFixed(2);
    }
  }

  void increaseDelay() {
    var v = delay.value + state.unit.value.step;
    updateDelay(v);
  }

  void decreaseDelay() {
    var v = delay.value - state.unit.value.step;
    updateDelay(v);
  }

  void updateDelay(double v) {
    if (v > 8) {
      v = 8;
    }
    if (v < 0) {
      v = 0;
    }
    timeDelay.timeDelays[index] = v;

    refreshDelayText();

    delay.value = v;
  }

  //发送数据
  _sendData() {
    var time = (delay.value * 100).toInt();
    logd('delay=$time');
    Msg.msgDelay(index, time, active: state.selectCH.value == index).send();
    Msg.msgParaphase(index, phase.value.toInt(),
            active: state.selectCH.value == index)
        .send();
  }

  ///同步link数据
  _asyncFirstLinkData() {
    if (state.linkedFirst.value == null) return;
    final linkedIndex = state.linkedFirst.value!;
    var linkedC = state.delayItemControllers[linkedIndex];
    for (var c in state.delayItemControllers) {
      if (!c.linked.value || c.index == linkedIndex) continue;
      c.level.volume = linkedC.level.volume;
      c.volume.value = linkedC.volume.value;
      c.mute.value = linkedC.mute.value;
      c.phase.value = linkedC.phase.value;
    }
  }

  void togglePhase() {
    phase.value = !phase.value;
  }

  ///切换激活状态
  void toggleActive({required int ch}) {
    active.value = !active.value;
  }

  void updateVolume(double v) {
    try {
      level.volume = v.toInt();
      volume.value = v;
      logger.d('updateVolume $v');
    } catch (e) {
      logger.d(e);
    }
  }

  void increaseVolume() {
    var v = level.volume;
    v++;
    if (v > 0) {
      v = 0;
    }
    updateVolume(v.toDouble());
  }

  void decreaseVolume() {
    var v = level.volume;
    v--;
    if (v < -20) {
      v = -20;
    }
    updateVolume(v.toDouble());
  }

  void updatePhase(bool v) {
    level.paraphase = v;
    phase.value = v;
  }

  void updateMute(bool v) {
    level.mute = v;
    mute.value = v;
  }
}
